package com.framework.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.framework.dao.active.ActiveAgentDao;
import com.framework.entity.sys.SysActive;
import com.framework.entity.sys.SysActiveAgent;
import com.framework.entity.sys.SysActiveInfo;
import com.framework.entity.sys.SysAgent;
import com.framework.exception.RRException;
import com.framework.exception.menu.RespCode;
import com.framework.page.PageUtils;
import com.framework.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wq
 */
@Service("activeAgentService")
@Transactional(rollbackFor = Exception.class)
public class ActiveAgentServiceImpl extends ServiceImpl<ActiveAgentDao, SysActiveAgent> implements ActiveAgentService {

	@Autowired
	private AgentService agentService;
	@Autowired
	private ActiveService activeService;
	@Autowired
	private SysActiveInfoService sysActiveInfoService;
	@Autowired
	private TerminalInfoService terminalInfoService;
	@Override
	public PageUtils queryHistoryList(Map<String, Object> params) {
		//开始时间
		Object startTime =params.get("startTime");
		//结束时间
		Object endTime=params.get("endTime");

		if ( startTime==null || "".equals(startTime) ){
			params.put("startTime",null);
		}
		if (endTime ==null || "".equals(endTime)){
			params.put("endTime",null);
		}
		List<Map<String, Object>> list = this.baseMapper.queryHistoryList(params);
		int totalCount=this.baseMapper.queryHistoryCount(params);
		int currPage=Integer.valueOf(params.get("page").toString());
		int pageSize=Integer.valueOf(params.get("limit").toString());
		PageUtils pageUtils=new PageUtils(list,totalCount,pageSize,currPage);
		return pageUtils;
	}

	@Override
	public Map<String, Object> queryOwnerActive(String token, Long activeId) {
		if(activeId == null){
			throw new RRException(RespCode.NOT_PARAM_ERROR);
		}
		Map<String,Object> result=new HashMap<>();
		SysAgent agent=agentService.queryAgentByToken(token);
		SysActive sysActive= activeService.queryActiveById(activeId);
		if(sysActive==null || sysActive.getIsDel().intValue()==1){
			throw  new RRException("9000","查无此活动");
		}
		//1.查出活动详情，得到开始结束时间
		List<SysActiveInfo> activeInfos = sysActiveInfoService.queryActiveInfoListByActiveId(activeId);
		if(activeInfos==null){
			throw new RRException("9000","未查询到活动详细信息");
		}
		//添加活动详情,是标准
		result.put("standard",activeInfos);
		Date startDate = activeInfos.get(0).getStartDate();
		Date endDate = activeInfos.get(0).getEndDate();
		Date currDate=new Date();
		//活动未开始
		if(startDate.after(currDate)){
			throw new RRException("9000","活动尚未开始");
		}
		//活动已结束
		if(currDate.after(endDate)){
			List<SysActiveAgent> sysActiveAgents=this.baseMapper.queryOwnerActive(agent.getAgentId(),activeId);
			if(sysActiveAgents==null){
				throw new RRException("9000","您未参与过此活动");
			}
			result.put("history",sysActiveAgents);
			return result;
		}
		//活动进行中,查询是否有记录，
		List<SysActiveAgent> sysActiveAgents=this.baseMapper.queryOwnerActive(agent.getAgentId(),activeId);
		//没有记录，则添加一条新纪录,从最低档开始
		if(sysActiveAgents==null){
			insertOwnerActive(agent.getAgentId(),activeId,activeInfos.get(0).getActiveInfoId());
			sysActiveAgents=this.baseMapper.queryOwnerActive(agent.getAgentId(),activeId);
		}
		for (int i = 0; i < sysActiveAgents.size(); i++) {
			SysActiveAgent sysActiveAgent =  sysActiveAgents.get(i);
			//找出未结算的记录，更新
			if(sysActiveAgent.getIsBalance().intValue()==1){
				queryAndUpdateOwnerActive(sysActiveAgent,activeId);
			}
		}
		result.put("history",sysActiveAgents);
		return result;
	}

	@Override
	public void queryAndUpdateOwnerActive(SysActiveAgent sysActiveAgent, Long activeId) {
		List<SysActiveInfo> list = sysActiveInfoService.queryActiveInfoListByActiveId(activeId);
		//查询个人的直属合伙人数量
		//本月的数量 2.上个月
		int type=1;
		List<SysAgent> subAgentList = agentService.queryRealSubAgent(sysActiveAgent.getAgentId(),type);
		Integer realSubNum=subAgentList.size();
		//查询有效激活机具
		//Integer realActivityNum=0;
		Long realActivityNum =subAgentList.stream()
					.filter(e->terminalInfoService.queryActivationCount(e.getAgentId(),2,1)>0)
				.count();


		sysActiveAgent.setRealSubNum(realSubNum);
		sysActiveAgent.setRealActivityNum(realActivityNum.intValue());
		list.stream()
				.filter(e->realSubNum>e.getSubNum()&& realActivityNum>e.getActivityNum())
				.forEach(e->sysActiveAgent.setActiveInfoId(e.getActiveInfoId()));

		this.baseMapper.updateById(sysActiveAgent);
	}

	@Override
	public SysActiveAgent queryNoBalanceActiveByAgentId(Long agentId, Long activeId) {
		return baseMapper.queryNoBalanceActiveByAgentId(agentId,activeId);
	}

	@Override
	public List<SysActiveAgent> queryAllNoBalance() {
		return baseMapper.queryAllNoBalance();
	}

	@Override
	public void insertOwnerActive(Long agentId, Long activeId,Long activeInfoId) {
		SysActiveAgent sysActiveAgent=new SysActiveAgent();
		sysActiveAgent.setAgentId(agentId);
		sysActiveAgent.setActiveId(activeId);
		sysActiveAgent.setRealActivityNum(0);
		sysActiveAgent.setState(0);
		sysActiveAgent.setActiveInfoId(activeInfoId);
		sysActiveAgent.setRealBuyNum(0);
		sysActiveAgent.setRealSubNum(0);
		sysActiveAgent.setCreateTime(new Date());
		this.baseMapper.insert(sysActiveAgent);
	}


}
